package com.instalinks.android.smspostservice.activity;

import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.instalinks.android.smspostservice.AppTabBaseActivity;
import com.instalinks.android.smspostservice.R;

public class HelpActivity extends AppTabBaseActivity {

	private ImageButton btnReloadHelp;
	private TextView txtContent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.initialize();
	}

	private void initialize() {
		this.setContentView(R.layout.help);

		txtContent = (TextView) this.findViewById(R.id.txtContent);
		btnReloadHelp = (ImageButton) this.findViewById(R.id.btnReloadHelp);
		btnReloadHelp.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				reloadHelp();
			}
		});

		String helpText = mAppCfg.getHelpText();

		if (helpText.length() > 0)
			txtContent.setText(Html.fromHtml(helpText));
		else {
			txtContent.setText(Html
					.fromHtml(getString(R.string.defaultHelpText)));
		}
	}

	private void reloadHelp() {
		if (mAppCfg.isConnectedToNetwork()) {
			(new SubTask("Downloading help content")).execute();
		} else {
			mAppCfg.alert(getString(R.string.network_error));
		}
	}

	private void setHelpContent(String content) {
		if (content.length() > 0) {
			this.txtContent.setText(Html.fromHtml(content));

			try {
				mAppCfg.setHelpText(content);
			} catch (Exception e) {
			}
			mAppCfg.alert("Updated with latest help content");
		} else {
			mAppCfg.alert("Could not find help content. Try after sometime.");
		}
	}


	String helpText =  "";
	@Override
	protected boolean doBackgroundWork() {
		this.helpText = mAppCfg.getHelpContent();

		if (this.helpText.toLowerCase().startsWith("error")) {
			this.helpText = "";
			return false;
		} else if (this.helpText.length()>0) {
			return true;
		} else {
			this.helpText = "";
			return true;
		}
	}

	@Override
	protected void doOnSuccess() {
		setHelpContent(helpText);
	}

	@Override
	protected void doOnFailure() {
		mAppCfg.alert("Error downloading help content. Try again");
	}

}
